package ch.fusun.baron.basic.client.ui.player;

import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.core.injection.ReInjector;
import ch.fusun.baron.data.DataListener;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.player.Player;
import ch.fusun.baron.player.api.PlayerService;

/**
 * 
 */
public class PersonSelectionDialog extends TitleAreaDialog implements
        DataListener {

    @Inject
    private transient PlayerService playerService;

    private final StructuredSelection selection = null;
    private SelectionTable<Player> selectionTable;

    /**
     * Kryo
     */
    public PersonSelectionDialog() {
        super(new Shell());
    }

    /**
     * @param parentShell
     *            the parent shell
     */
    public PersonSelectionDialog(Shell parentShell) {
        super(parentShell);
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        ReInjector.getInstance().reInject(this);
        playerService.addDataListener(this);

        selectionTable = new SelectionTable<Player>(parent,
                PersonColumns.values());

        playerService.addDataListener(this);
        selectionTable.setInput(playerService.getAllPlayers());

        GridLayout layout = new GridLayout();
        parent.setLayout(layout);

        return parent;
    }

    @Override
    protected boolean isResizable() {
        return true;
    }

    /**
     * @return The selection made
     */
    public StructuredSelection getSelection() {
        return selection;
    }

    @Override
    public void dataChanged(DataUpdate update) {
        Shell shell = getShell();
        if (shell != null) {
            shell.getDisplay().asyncExec(new Runnable() {

                @Override
                public void run() {
                    selectionTable.setInput(playerService.getAllPlayers());
                }
            });
        }
    }

    @Override
    public boolean close() {
        playerService.removeDataListener(this);
        return super.close();
    }
}
